package com.by.wx.controller;

import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.by.common.conf.TelConfMager;
import com.by.common.cont.TelConst;
import com.by.common.util.HttpUtil;
import com.by.common.util.MD5Utils;
import com.by.common.util.SmsUtils;
import com.by.common.util.ThreadLocalDateUtil;
import com.by.common.vo.JsonResult;
import com.by.common.vo.PhoneRoomResult;
import com.by.wx.entity.PhoneCode;
import com.by.wx.entity.PhoneMember;
import com.by.wx.entity.PhoneMemberResult;
import com.by.wx.service.PhoneSmsService;
import com.by.wx.service.PhoneMemberService;
import com.by.wx.service.PhoneService;
import com.by.wx.service.WxinService;

//ok
@Controller
@RequestMapping("/verify/")
public class PhoneController {

	public static Log log = LogFactory.getLog(PhoneController.class);

	@Autowired
	private PhoneService phoneService;
	@Autowired
	private WxinService wxinService;
	@Autowired
	private PhoneMemberService phoneMemberService;
	@Autowired
	private PhoneSmsService phoneSmsService;

	// private static String rod = HttpUtil.smsCode();
	@RequestMapping("pcode")
	public String pcode(Model m) {
		String sex = "1";
		m.addAttribute("sex", sex);
		return "wxin/index_phone_regiest";
	}

	@RequestMapping("redirctToNoConl")
	public String redirctToNoConl() {
		return "wxin/no_control";
	}

	@RequestMapping("redirctToNoRooConl")
	public String redirctToNoRooConl() {
		return "wxin/no_room_control";
	}

	@RequestMapping("phonereg")
	public String phonereg() {
		return "wxin/index_phone_regiest";
	}

	@RequestMapping("phoneJump")
	public String phoneJump() {
		return "wxin/jump_phone_regiest";
	}

	@RequestMapping("jumpToVerifyPhone")
	public String jumpToVerifyPhone() {
		return "wxin/ft_verify_phone_number";
	}

	@RequestMapping("wxfail")
	public String wxfail() {
		return "wxin/wxfail";
	}

	@RequestMapping("wxAddMembSuccess")
	public String wxAddMembSuccess() {
		return "wxin/wxsuccess_member_add";
	}

	@RequestMapping("wxAddSuccessToLive")
	public String wxAddSuccessToLive() {
		return "wxin/regiest_success_member_jump";
	}

	@RequestMapping("wxsuccess")
	public String wxsuccess() {
		return "wxin/wxsuccess";
	}
	
	@RequestMapping("sendSmsByAliyun")
	@ResponseBody
	public JsonResult sendSmsByAliyun(String phone) {
		String rod = phoneSmsService.findCreateAliyunPhoneSmsByMimutes(phone);
		log.info("获取到阿里云的短信验证码为：" + rod);

		try {
			if (!TelConfMager.getBoolean(TelConst.ALIYUN_COM_PHONE_SMS_LOCAL)) {
				if (TelConfMager.getBoolean(TelConst.ALIYUN_COM_PHONE_SMS_SEND_LIMIT_OPEN)) {
					List<PhoneCode> list = phoneService.dofind(phone);
					List<String> time = new ArrayList<>();
					Date d = new Date();
					String[] sp = d.toString().split(" ");
					String today = sp[5] + "-" + sp[1] + "-" + sp[2];
					String count = null;
					out: for (PhoneCode pp : list) {
						// time.add(String.valueOf(pp.getGenerateTime()));
						String[] info = pp.getGenerateTime().toString().split(" ");
						for (int i = 0; i < info.length; i++) {
							count = info[5] + "-" + info[1] + "-" + info[2];
							if (!today.contains(count)) {
								continue out;
							}
						}
						time.add(count);
					}
					// System.out.println("size="+time.size());
					log.info("该手机" + phone + "获取验证码的的次数为=" + time.size() + "次");
					int limitQuality = TelConfMager.getInteger(TelConst.ALIYUN_COM_PHONE_SMS_SEND_LIMIT_QUANTITY);
					if (time.size() >= 0 && time.size() < limitQuality) {
						String flag = getAliyunSmsSendTemplateByPhone(phone);
						if ("success".equals(flag)) {
							log.info("验证码已发送给" + phone + "该手机，请注意接收!");
							return new JsonResult("验证码已发送给" + phone + "该手机，请注意接收!");
						} else {
							log.info("该手机" + phone + "获取验证码过于频繁，请注稍后再试!");
							return new JsonResult("该手机" + phone + "获取验证码过于频繁，请注稍后再试!");
						}
					} else {
						return new JsonResult(0, "该手机" + phone + "今天获取手机验证码的次数超过" + limitQuality + "次，请明天再来!");
					}
				} else {
					getAliyunSmsSendTemplateByPhone(phone);
					String flag = getAliyunSmsSendTemplateByPhone(phone);
					if ("success".equals(flag)) {
						log.info("验证码已发送给" + phone + "该手机，请注意接收!");
						return new JsonResult("验证码已发送给" + phone + "该手机，请注意接收!");
					} else {
						log.info("该手机" + phone + "获取验证码过于频繁，请注稍后再试!");
						return new JsonResult("该手机" + phone + "获取验证码过于频繁，请注稍后再试!");
					}
				}
			}
		} catch (ClientException e) {
			e.printStackTrace();
		}

		return new JsonResult();
	}

	/**
	 * 阿里云短信示例
	 * 
	 * @param phone
	 * @throws ClientException
	 */
	public String getAliyunSmsSendTemplateByPhone(String phone) throws ClientException {
		System.setProperty(TelConfMager.getProperty(TelConst.ALIYUN_COM_PHONE_SMS_PROPERTY_COLLECT), TelConfMager.getProperty(TelConst.ALIYUN_COM_PHONE_SMS_PROPERTY_COLLECT_MILLISECONDS));
		System.setProperty(TelConfMager.getProperty(TelConst.ALIYUN_COM_PHONE_SMS_PROPERTY_READ), TelConfMager.getProperty(TelConst.ALIYUN_COM_PHONE_SMS_PROPERTY_READ_MILLISECONDS));
		// 初始化ascClient需要的几个参数
		final String product = TelConfMager.getProperty(TelConst.ALIYUN_COM_PHONE_SMS_ASC_CLIENT_PRODUCT);//短信API产品名称（短信产品名固定，无需修改）
		final String domain = TelConfMager.getProperty(TelConst.ALIYUN_COM_PHONE_SMS_ASC_CLIENT_DOMAIN);//短信API产品域名（接口地址固定，无需修改）
		// 替换成你的AK
		final String accessKeyId = TelConfMager.getProperty(TelConst.ALIYUN_COM_PHONE_SMS_ACCESS_KEY_ID);//你的accessKeyId
		final String accessKeySecret = TelConfMager.getProperty(TelConst.ALIYUN_COM_PHONE_SMS_ACCESS_KEY_SECRET);//你的accessKeySecret
		// 初始化ascClient,暂时不支持多region（请勿修改）
		IClientProfile profile = DefaultProfile.getProfile(TelConfMager.getProperty(TelConst.ALIYUN_COM_PHONE_SMS_REGION_ID), accessKeyId, accessKeySecret);
		DefaultProfile.addEndpoint(TelConfMager.getProperty(TelConst.ALIYUN_COM_PHONE_SMS_REGION_ID), TelConfMager.getProperty(TelConst.ALIYUN_COM_PHONE_SMS_REGION_ID), product, domain);
		IAcsClient acsClient = new DefaultAcsClient(profile);
		// 组装请求对象
		SendSmsRequest request = new SendSmsRequest();
		// 使用post提交
		request.setMethod(MethodType.POST);
		// 必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式；发送国际/港澳台消息时，接收号码格式为00+国际区号+号码，如“0085200000000”
		request.setPhoneNumbers(phone);
		// 必填:短信签名-可在短信控制台中找到
		request.setSignName(TelConfMager.getProperty(TelConst.ALIYUN_COM_PHONE_SMS_ASC_COMPANY_SIGN_NAME));
		// 必填:短信模板-可在短信控制台中找到，发送国际/港澳台消息时，请使用国际/港澳台短信模版
		request.setTemplateCode(TelConfMager.getProperty(TelConst.ALIYUN_COM_PHONE_SMS_ASC_INTERNAL_HK_TEMPLATE_CODE));
		// 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
		// 友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
		// request.setTemplateParam("{\"code\":\"988756\"}");
		String msgCode = SmsUtils.generateAliyunMsgCode();
		request.setTemplateParam("{\""+TelConfMager.getProperty(TelConst.ALIYUN_COM_PHONE_SMS_ASC_NATIVE_TEMPLATE_PARAM_FIREST)+"\":\"" + msgCode + "\"}");
		// 请求失败这里会抛ClientException异常
		SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
		if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
			// 请求成功
			phoneService.saveCode(phone, msgCode);
			return "success";
		} else {
			// System.out.println("=====fail=======");
			log.error("getAliyunSmsSendTemplateByPhone此方法中，请求失败！！=====fail=======");
			return "fail";
		}
	}

	@RequestMapping("alisms")
	@ResponseBody
	public JsonResult alisms(String phone) {
		String crod = phoneSmsService.findCreateAliyunPhoneSmsByMimutes(phone);
		return new JsonResult(crod);
	}

	/**
	 * 秒滴科技发送短信接口
	 * 
	 * @param phone
	 * @return
	 */
	@RequestMapping("sendThesms")
	@ResponseBody
	public JsonResult sendThesms(String phone) {
		String rod = phoneSmsService.findCreatePhoneSmsByMimutes(phone, 1);
		// System.out.println("as="+rod);
		List<PhoneCode> list = phoneService.dofind(phone);
		List<String> time = new ArrayList<>();
		Date d = new Date();
		String[] sp = d.toString().split(" ");
		String today = sp[5] + "-" + sp[1] + "-" + sp[2];
		String count = null;
		out: for (PhoneCode pp : list) {
			// time.add(String.valueOf(pp.getGenerateTime()));
			String[] info = pp.getGenerateTime().toString().split(" ");
			for (int i = 0; i < info.length; i++) {
				count = info[5] + "-" + info[1] + "-" + info[2];
				if (!today.contains(count)) {
					continue out;
				}
			}
			time.add(count);
		}
		// System.out.println("size="+time.size());
		if (time.size() < 3 && time.size() >= 0) {
			if (!TelConfMager.getBoolean(TelConst.MIAODIYUN_COM_PHONE_SMS_MESSAGE_LOCAL)) {
				String tmpSmsContent = null;
				try {
					phoneService.saveCode(phone,rod);
					tmpSmsContent = URLEncoder.encode(TelConfMager.getProperty(TelConst.MIAODIYUN_COM_PHONE_SMS_MESSAGE_TEMPLATE).replace("XXXX", TelConfMager.getProperty(TelConst.MIAODIYUN_COM_PHONE_SMS_MESSAGE_COMPANY))
							.replace("{1}", rod).replace("{2}", String.valueOf(Integer.parseInt(TelConfMager.getProperty(TelConst.MIAODIYUN_COM_PHONE_FAILURE_TIME_MILLIS))/10000)), "UTF-8");
				}catch(Exception e){
					e.printStackTrace();
				}
				String url = TelConfMager.getProperty(TelConst.MIAODIYUN_COM_PHONE_REST_HANDLE_URL_PREFIX)+TelConfMager.getProperty(TelConst.MIAODIYUN_COM_PHONE_REST_SMS_URL_SUFFIX);
				String body = "accountSid=" + TelConfMager.getProperty(TelConst.MIAODIYUN_COM_PHONE_ACCOUNT_SID) 
				+ "&to=" + phone + "&smsContent=" + tmpSmsContent + HttpUtil.createCommonParam();
				
				// 提交请求
				String result = HttpUtil.post(url, body);
				log.info("sendThesms秒滴科技验证码提交请求result：" + System.lineSeparator() + result);
				// System.out.println("result:" + System.lineSeparator() + result);
			}

			return new JsonResult("验证码已发送给" + phone + "该手机，请注意接收!");
		} else {
			return new JsonResult(0, "该手机" + phone + "获取手机验证码的次数超过多次，请明天再来!");
		}
	}
	
	@RequestMapping("verifyCode")
	@ResponseBody
	public JsonResult verifyCode(String phone, String code) {
		// System.out.println("code="+code);
		// String rod =
		// phoneSmsService.findCreateAliyunPhoneSmsByMimutes(phone);
		List<PhoneCode> entity = phoneSmsService.doFindAliyunSmsCodeByPhone(phone);
		// System.out.println(entity.get(0).getCode());
		if (entity.get(0).getCode().equals(code)) {
			return new JsonResult(1, "输入的验证码正确", true);
		} else {
			return new JsonResult(0, "输入的验证码不正确，请重新输入！", false);
		}
	}

	@RequestMapping("doFtVerPhoneMember")
	@ResponseBody
	public JsonResult doFtVerPhoneMember(Model m, HttpSession session, String openid, String nickname, String phone,
			String code, HttpServletResponse response) throws ParseException {
		List<PhoneCode> verifyEntity = phoneSmsService.doFindAliyunSmsCodeByPhone(phone);
		Date date = new Date();
		long compNow = date.getTime();
		long hisTime = ThreadLocalDateUtil.parse(ThreadLocalDateUtil.formatDate(verifyEntity.get(0).getGenerateTime())).getTime();
		long minuteTime = Long.valueOf(TelConfMager.getProperty(TelConst.ALIYUN_COM_PHONE_SMS_VALID_PAST_SECONDS))*1000L;
		long flagTime = hisTime + minuteTime;
		if (verifyEntity.get(0).getCode().equals(code)) {
			if (compNow < flagTime) {
				List<PhoneMember> flagMemInfos = phoneService.doFindMemInfoByPhone(phone);
				if (flagMemInfos.size() == 0) {
					log.info("doFtVerPhoneMember该手机" + phone + "找不到对应的会员信息，跳去注册页面wxin/no_control.jsp");
					return new JsonResult(4, "此id获取不到对应的会员信息，跳去注册页面", flagMemInfos);
				} else {
					List<PhoneRoomResult> AllRoomNotes = phoneService.findRoomrecordByMemberPhone(phone);
					if (AllRoomNotes.size() == 0) {
						// System.out.println("no member no room");
						// response.sendRedirect("./redirctToNoConl.do");
						log.info("doFtVerPhoneMember该手机" + phone + "找到的对应的会员信息，但是找不到此信息的对应的房间信息，无法授权控制，wxin/no_room_control.jsp");
						return new JsonResult(3, "此id获取到的会员信息没有进行入住操作", AllRoomNotes);
					} else {
						Integer flagRoomConditionId = AllRoomNotes.get(0).getVipId();
						phoneMemberService.updThePhoneMemberByPhone(openid, nickname, phone);
						List<PhoneRoomResult> AllRoomLogs = wxinService.findCheckRoomLineById(flagRoomConditionId);
						String roomNum = null;
						for (PhoneRoomResult res : AllRoomLogs) {
							if (StringUtils.isEmpty(res.getEnd())) {
								roomNum = res.getRoomNumber();
							}
						}
						if (StringUtils.isEmpty(roomNum)) {
							// response.sendRedirect("./redirctToNoRooConl.do");
							log.info("doFtVerPhoneMember该手机" + phone + "找到的对应的会员信息，但是找不到此信息的对应的房间信息，无法授权控制，wxin/no_room_control.jsp");
							return new JsonResult(3, "此id获取到的会员信息没有进行入住操作", AllRoomLogs);
						} else {
							// List<PhoneMember> entity =
							// wxinService.findPrivilegeByOpenidVerifyToSkipHref(openid);
							// String coded = entity.get(0).getCoded();
							List<PhoneCode> lastlist = phoneMemberService.doFindLasttimeByPhone(phone, 1);
							String codes = lastlist.get(0).getCode();
							Timestamp time = Timestamp.valueOf(ThreadLocalDateUtil.formatDate(lastlist.get(0).getGenerateTime()));
							Timestamp lastCodeTime = Timestamp.valueOf(String.valueOf(time).split("\\.")[0]);
							wxinService.updatePhoCodeByOpenid(codes, lastCodeTime, openid);

							phone = AllRoomNotes.get(0).getPhone();
							String username = AllRoomNotes.get(0).getUsername();
							session.setAttribute("phone", phone);
							session.setAttribute("username", username);

							String datestamp = ThreadLocalDateUtil.formatDate(new Date());
							Integer rid = AllRoomLogs.get(0).getVipId();
							String sign = MD5Utils.generateMD5SignString(String.valueOf(rid), roomNum, datestamp);
							session.setAttribute("timestamp", datestamp);
							session.setAttribute("renter_id", rid);
							session.setAttribute("room_id", roomNum);
							session.setAttribute("sign", sign);
							log.info("此手机" + phone + "获取会员信息成功");
							return new JsonResult(1, "获取会员信息成功", AllRoomNotes);
						}
					}
				}
			} else {
				// return "wxin/wxfail";
				// System.out.println("---短信验证失败---");
				log.error("doFtVerPhoneMember方法中，该手机" + phone + "该验证码已经超时，请重新获取！");
				return new JsonResult(5, "该验证码已经超时，请重新获取！");
			}
		} else {
			log.error("doFtVerPhoneMember方法中，该手机" + phone + "短信验证失败");
			return new JsonResult(0, "短信验证失败或不正确");
		}
	}

	@RequestMapping("doVerPhoneMember")
	@ResponseBody
	public JsonResult doVerPhoneMember(HttpSession session, String openid, String nickname, String phone, String code)
			throws ParseException {
		// String rod = phoneSmsService.findCreateAliyunPhoneSmsByMimutes(phone);
		List<PhoneCode> verifyEntity = phoneSmsService.doFindAliyunSmsCodeByPhone(phone);
		Date date = new Date();
		long compNow = date.getTime();
		long hisTime = ThreadLocalDateUtil.parse(ThreadLocalDateUtil.formatDate(verifyEntity.get(0).getGenerateTime())).getTime();
		long minuteTime = Long.valueOf(TelConfMager.getProperty(TelConst.ALIYUN_COM_PHONE_SMS_VALID_PAST_SECONDS))*1000L;
		long flagTime = hisTime + minuteTime;
		if (verifyEntity.get(0).getCode().equals(code)) {
			if (compNow < flagTime) {
				// wxinService.updatePhoCodeByOpenid(rcode, openid);
				// List<PhoneMember> entity =
				// wxinService.findPrivilegeByOpenidVerifyToSkipHref(openid);
				// String codes = entity.get(0).getCoded();
				List<PhoneCode> lastlist = phoneMemberService.doFindLasttimeByPhone(phone, 1);
				String codes = lastlist.get(0).getCode();
				Timestamp time = Timestamp.valueOf(ThreadLocalDateUtil.formatDate(lastlist.get(0).getGenerateTime()));
				Timestamp lastCodeTime = Timestamp.valueOf(String.valueOf(time).split("\\.")[0]);
				wxinService.updatePhoCodeByOpenid(codes, lastCodeTime, openid);

				List<PhoneRoomResult> entity = wxinService.findCheckRoomLineByPhone(phone);
				String roomNum = entity.get(0).getRoomNumber();
				phone = entity.get(0).getPhone();
				String username = entity.get(0).getUsername();
				session.setAttribute("phone", phone);
				session.setAttribute("username", username);

				String datestamp = ThreadLocalDateUtil.formatDate(new Date());
				Integer rid = entity.get(0).getVipId();
				String sign = MD5Utils.generateMD5SignString(String.valueOf(rid), roomNum, datestamp);
				session.setAttribute("timestamp", datestamp);
				session.setAttribute("renter_id", rid);
				session.setAttribute("room_id", roomNum);
				session.setAttribute("sign", sign);
				// return "wxin/wxsuccess";
				return new JsonResult("短信验证成功");
			} else {
				// return "wxin/wxfail";
				// System.out.println("---短信验证失败---");
				log.error("doVerPhoneMember方法中，该手机" + phone + "该验证码已经超时，请重新获取！");
				return new JsonResult(5, "改验证码已经超时，请重新获取！");
			}
		} else {
			log.error("doVerPhoneMember方法中，该手机" + phone + "该验证码已经超时，请重新获取！");
			return new JsonResult(0, "短信验证失败或不正确");
		}
	}
	
	@RequestMapping("receiveThesms")
	@ResponseBody
	public JsonResult receiveThesms(String phone, String rcode) {
		return new JsonResult();
	}

	@RequestMapping("createCode")
	@ResponseBody
	public JsonResult createCode(String phone) {
		return new JsonResult();
	}

	@RequestMapping("doSaveWxPhoMember")
	@ResponseBody
	public JsonResult doSaveWxPhoMember(PhoneMember entity) {
		List<PhoneCode> verifyEntity = phoneSmsService.doFindAliyunSmsCodeByPhone(entity.getPhone());
		try {
			Date date = new Date();
			long compNow = date.getTime();
			long hisTime = ThreadLocalDateUtil.parse(ThreadLocalDateUtil.formatDate(verifyEntity.get(0).getGenerateTime())).getTime();
			long minuteTime = Long.valueOf(TelConfMager.getProperty(TelConst.ALIYUN_COM_PHONE_SMS_VALID_PAST_SECONDS)) * 1000L;
			long flagTime = hisTime + minuteTime;
			if (compNow < flagTime) {
				if (verifyEntity.get(0).getCode().equals(entity.getCoded())) {
					int row = phoneMemberService.doSaveWxPhoMember(entity);
					if (row == 0) {
						log.error("doSaveWxPhoMember出现异常，添加失败");
						return new JsonResult(0, "添加失败");
					} else {
						return new JsonResult("添加成功");
					}
				} else {
					log.error("doSaveWxPhoMember短信验证失败");
					return new JsonResult(0, "短信验证失败");
				}
			} else {
				log.error("doSaveWxPhoMember该验证码已经超时，请重新获取！");
				return new JsonResult(5, "该验证码已经超时，请重新获取！");
			}

		} catch (ParseException e) {
			e.printStackTrace();
		}
		log.error("doSaveWxPhoMember未知错误！");
		return new JsonResult(7, "未知错误");
	}

	@RequestMapping("doSaveWxMemPhoneCode")
	@ResponseBody
	public JsonResult doSaveWxMemPhoneCode(PhoneMember entity) {
		List<PhoneCode> verifyEntity = phoneSmsService.doFindAliyunSmsCodeByPhone(entity.getPhone());
		try {
			Date date = new Date();
			long compNow = date.getTime();
			long hisTime = ThreadLocalDateUtil.parse(ThreadLocalDateUtil.formatDate(verifyEntity.get(0).getGenerateTime())).getTime();
			long minuteTime = Long.valueOf(TelConfMager.getProperty(TelConst.ALIYUN_COM_PHONE_SMS_VALID_PAST_SECONDS)) * 1000L;
			long flagTime = hisTime + minuteTime;
			if (compNow < flagTime) {
				if (verifyEntity.get(0).getCode().equals(entity.getCoded())) {
					int row = phoneMemberService.doSaveWxMemPhoneCode(entity);
					if (row == 0) {
						log.error("doSaveWxPhoMember出现异常，添加失败");
						return new JsonResult(0, "添加失败");
					} else {
						return new JsonResult("添加成功");
					}
				} else {
					log.error("doSaveWxPhoMember短信验证失败");
					return new JsonResult(0, "短信验证失败");
				}
			} else {
				log.error("doSaveWxPhoMember该验证码已经超时，请重新获取！");
				return new JsonResult(5, "该验证码已经超时，请重新获取！");
			}

		} catch (ParseException e) {
			e.printStackTrace();
		}
		log.error("doSaveWxPhoMember未知错误！");
		return new JsonResult(7, "未知错误");
	}
	
	@RequestMapping("doRegCheckopenidHref")
	@ResponseBody
	public JsonResult doRegCheckopenidHref(String openid, HttpSession session) {
		List<PhoneMember> entity = wxinService.findPrivilegeByOpenidVerifyToSkipHref(openid);
		if (entity.size() == 0) {
			return new JsonResult(2, "此openid没有对应记录", entity);
		}
		// System.out.println(entity.get(0).getCoded());
		if (entity.get(0).getCoded() == null || entity.get(0).getCoded() == "") {
			return new JsonResult(0, "此openid对应的记录没有获取到验证码", entity);
		}
		String phone = entity.get(0).getPhone();
		if (StringUtils.isEmpty(phone)) {
			return new JsonResult(3, "此openid对应手机号码为空", entity);
		}
		List<PhoneRoomResult> roomMemberInfos = wxinService.findCheckRoomLineByPhone(phone);
		if (roomMemberInfos.size() == 0) {
			return new JsonResult(4, "此openid对应手机号码的房间号为空", entity);
		}
		String roomNum = roomMemberInfos.get(0).getRoomNumber();
		if (StringUtils.isEmpty(roomNum)) {
			return new JsonResult(5, "此openid对应手机号码的房间号为空", entity);
		}
		try {
			phone = roomMemberInfos.get(0).getPhone();
			String username = roomMemberInfos.get(0).getUsername();
			session.setAttribute("phone", phone);
			session.setAttribute("username", username);

			String datestamp = ThreadLocalDateUtil.formatDate(new Date());
			Integer rid = roomMemberInfos.get(0).getVipId();
			String sign = MD5Utils.generateMD5SignString(String.valueOf(rid), roomNum, datestamp);
			session.setAttribute("timestamp", datestamp);
			session.setAttribute("renter_id", rid);
			session.setAttribute("room_id", roomNum);
			session.setAttribute("sign", sign);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return new JsonResult(1, "此openid找到了对应的验证码记录", entity);
	}
	
	
	@RequestMapping("ttest")
	@ResponseBody
	public JsonResult ttest(String phone) throws ParseException{
		List<PhoneCode> entity = phoneMemberService.updatetimeTest(phone);
		List<PhoneCode> lastlist = phoneMemberService.doFindLasttimeByPhone(phone,1);
		
		Timestamp time = Timestamp.valueOf(ThreadLocalDateUtil.formatDate(lastlist.get(0).getGenerateTime()));
		Timestamp lastCodeTime =Timestamp.valueOf(String.valueOf(time).split("\\.")[0]);
		int row = wxinService.updatePhoCodeByOpenid("123456", lastCodeTime, "Q12");
		List<PhoneMember> flagRoomVerf = wxinService.findPrivilegeByOpenidVerifyToSkipHref("Q12");
		String ss = ThreadLocalDateUtil.formatDate(flagRoomVerf.get(0).getLastCodeTime());
		Date da = flagRoomVerf.get(0).getLastCodeTime();
		Date ti = ThreadLocalDateUtil.parse(ThreadLocalDateUtil.formatDate(flagRoomVerf.get(0).getLastCodeTime()));
		return new JsonResult(entity);
	}
	
	
	
	@RequestMapping("verifyPhoneCheck")
	@ResponseBody
	public JsonResult verifyPhoneCheck(String phone) {
		List<PhoneMember> entity = phoneService.verifyPhoneCheck(phone);
		if (entity.size() != 0) {
			log.error("verifyPhoneCheck该手机号码" + phone + "已经注册过，请到前台进行登记入住！");
			return new JsonResult(0, "该手机号码已经注册过，请到前台进行登记入住！");
		}
		return new JsonResult("改手机号码还没有注册过，可以进行注册使用");
	}

	@RequestMapping("doDelUpdateOpenid")
	@ResponseBody
	public JsonResult doDelUpdateOpenid(String openid) {
		int row = phoneMemberService.doDelUpdateOpenid(openid);
		return new JsonResult(row + "条openid操作成功");
	}

	@RequestMapping("doCheckVerifyRoomJumpOpenid")
	@ResponseBody
	public JsonResult doCheckVerifyRoomJumpOpenid(String openid, HttpSession session) {
		List<PhoneMemberResult> entity = phoneMemberService.doCheckVerifyRoomJumpOpenid(openid);
		if (StringUtils.isEmpty(entity) || entity.size() == 0) {
			return new JsonResult(0, "获取信息失败！！");
		}
		try {
			List<PhoneCode> verifyEntity = phoneSmsService.findHistoryPhoneSmsByOpenid(openid);
			Date date = new Date();
			long compNow = date.getTime();
			long hisTime = ThreadLocalDateUtil.parse(ThreadLocalDateUtil.formatDate(verifyEntity.get(0).getGenerateTime())).getTime();
			long minuteTime = Long.valueOf(TelConfMager.getProperty(TelConst.ALIYUN_COM_PHONE_SMS_VALID_PAST_SECONDS)) * 1000L;
			long flagTime = hisTime + minuteTime;
			
			for (PhoneMemberResult pem : entity) {
				if (!StringUtils.isEmpty(pem.getRoomNumber())) {
					if (StringUtils.isEmpty(pem.getEnd())) {
						if (compNow > flagTime) {
							// session.setAttribute("openid", openid);
							return new JsonResult(5, "该验证码时效超时，请重新获取认证！！", false);
						}
						// List<PhoneCode> lastlist =
						// phoneSmsService.doFindCheckVerifyCodeByOpenid(openid);
						String code = verifyEntity.get(0).getCode();
						Timestamp lastCodeTime = Timestamp.valueOf(ThreadLocalDateUtil.formatDate(verifyEntity.get(0).getGenerateTime()));
						wxinService.updatePhoCodeByOpenid(code, lastCodeTime, openid);

						String phone = pem.getPhone();
						String username = pem.getUsername();
						session.setAttribute("phone", phone);
						session.setAttribute("username", username);

						String datestamp = ThreadLocalDateUtil.formatDate(new Date());
						Integer rid = pem.getVipId();
						String roomNum = pem.getRoomNumber();
						String sign = MD5Utils.generateMD5SignString(String.valueOf(rid), roomNum, datestamp);
						session.setAttribute("timestamp", datestamp);
						session.setAttribute("renter_id", rid);
						session.setAttribute("room_id", roomNum);
						session.setAttribute("sign", sign);
						// Timestamp timestamp =
						// Timestamp.valueOf(ThreadLocalDateUtil.formatDate(ThreadLocalDateUtil.parse(datestamp)));
						// wxinService.updateSessionTimeSignByOpenid(timestamp,sign,openid);

						return new JsonResult(1, "入住" + pem.getRoomNumber() + "号房间成功！", true);
					}
				}
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return new JsonResult(0, "入住失败！！", false);
	}
	
	
	@RequestMapping("template")
	@ResponseBody
	public JsonResult template(String phone) {
		// int row = phoneService.saveCode(phone,rod);
		// String tmpSmsContent = null;
		// try{
		// String rod = "354845";
		// tmpSmsContent = URLEncoder.encode(smsContent.replace("{1}",
		// rod).replace("{2}", "30"), "UTF-8");
		// }catch(Exception e){
		// e.printStackTrace();
		// }
		// String url = "https://api.miaodiyun.com/20150822" + operation;
		// String body = "accountSid=" + accountSid + "&to=" + to +
		// "&smsContent=" + tmpSmsContent
		// + HttpUtil.createCommonParam();
		//
		// // 提交请求
		// String result = HttpUtil.post(url, body);
		return new JsonResult(phone);
	}

	// @RequestMapping("receiveThesms")
	// public String receiveThesms(final HttpServletRequest request){
	// String phone=request.getParameter("phone");
	// int times=userService.messageSendToday(phone); //二次验证，单个手机号每日发送上限
	// if(times <= MAX_PER_DAY){
	// String checkCode=GenerateRandomCode.createRandomNumber(6);
	// final HttpSession httpSession=request.getSession();
	// httpSession.setAttribute("checkCode",checkCode);
	// CheckCodeMessage checkCodeMessage=new CheckCodeMessage(phone,checkCode);
	// try {
	// HttpSender.batchSend(checkCodeMessage);
	// //TimerTask实现5分钟后从session中删除checkCode
	// final Timer timer=new Timer();
	// timer.schedule(new TimerTask() {
	// @Override
	// public void run() {
	// httpSession.removeAttribute("checkCode");
	// timer.cancel();
	// }
	// },5*60*1000);
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// return "index";
	// }
	// }
	
}
